package com.zheng.durid.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.zheng.durid.context.SpringContextUtil;
import com.zheng.zk.Curator;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.NodeCache;
import org.apache.curator.framework.recipes.cache.NodeCacheListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;


/**
 *  @author: zheng
 *  @Date: 2020-07-02 23:23
 *  @Description:
 */

public class DruidSourceConfig {
    private static CuratorFramework curatorFramework= Curator.getCuratorFramework();
    private static DruidDataSource druidDataSource = null;

    public static DataSource setDataSource(String url,String userName,String password) throws Exception {
        druidDataSource= new DruidDataSource();
        druidDataSource.setUrl(url);
        druidDataSource.setUsername(userName);
        druidDataSource.setPassword(password);
        return druidDataSource;
    }

    public static void registListener() throws Exception {
        NodeCache nodeCache=new NodeCache(curatorFramework,"/mysqlConfig",false);
        nodeCache.getListenable().addListener(new NodeCacheListener() {
            @Override
            public void nodeChanged() throws Exception {
                byte[] data=nodeCache.getCurrentData().getData();
                String config=new String(data);
                String [] configs=config.split(",");
                String url=configs[0];
                String userName=configs[1];
                String password=configs[2];
                System.out.println("url"+url);
                setDataSource(url,userName,password);
            }
        });
        nodeCache.start();
    }

    public static DruidDataSource getInstance() {
        return druidDataSource;
    }



}
